package com.springboot.admin.schedule;

import com.springboot.admin.entity.PagesDto;
import com.springboot.admin.mail.MailSenderBoot;
import com.springboot.admin.mapper.PagesDao;
import com.springboot.admin.mapper.WebStatsDao;
import com.springboot.admin.service.AccountService;
import com.springboot.admin.service.PagesSerice;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;

@Component
@Slf4j
public class MySchedule {
    @Autowired
    MailSenderBoot mailSenderBoot;
    @Autowired
    PagesSerice pagesSerice;
    @Autowired
    WebStatsDao webStatsDao;
    @Autowired
    AccountService accountService;
    @Autowired
    PagesDao pagesDao;

    @Scheduled(cron = "0 30 20 1/1 * ? ")
    public void getBakToMail() {

        // 每晚20：30点半备份数据库文件到邮件
        Date d = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String currDate = (String) sdf.format(d);

        Map siteInfo = accountService.getSiteInfo();
        String realPath = (String) siteInfo.get("bakRealUrl");
        //  String realPath = "/Users/wilkwo/Downloads/xhdpi";
        File dir =new File(realPath);//浏览F盘a文件夹下的所有内容
        File[] files=dir.listFiles();   //列出所有的子文件
        for(File file :files) {
            if(file.isFile()){
                //如果是文件，则输出文件名字
                log.info("fileName===" + file.getName());
                String fileName = file.getName();
                String filePath = file.toString();
                int index = fileName.indexOf(currDate);
                if (index > -1){
                    mailSenderBoot.sendAttachmentsMail((String) siteInfo.get("siteEmail"), "备份文件", "备份数据库文件到邮箱", filePath);
                }
            }
        }


    }

    @Scheduled(cron = "0 0 */2 * * ? ")
    public void saveEveryDayViews() {
        // 每两个小时更新统计数据
        Map map = new HashMap();
        // 查所有访问量
        map.put("allViews", pagesSerice.getCountViews());
        // 查所有文章
        map.put("allpages", pagesSerice.getAllCount());
        // 查当天数据
        map.put("dayViews",webStatsDao.getViewsByDate());

        map.put("dayIp",webStatsDao.getViewsByIp());

        webStatsDao.delExistViews();

        webStatsDao.saveEveryDayViews(map);

    }

    // @Scheduled(cron = "*/5 * * * * ?")
    @Scheduled(cron = "0 30 23 1/1 * ? ")
    public void updateUUID() {
        List<PagesDto> list = pagesDao.getAllPost();
        for (PagesDto pagesDto : list){
            String uid = UUID.randomUUID().toString();
            int id  = pagesDto.getId();
            pagesDao.updateUUIDByid(uid,id);
        }
    }
}
